﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace MultiApp.UserControls
{
    public sealed partial class CurrencyControl : UserControl
    {
        Windows.ApplicationModel.Resources.ResourceLoader loader = new Windows.ApplicationModel.Resources.ResourceLoader("Strings");
        public CurrencyControl()
        {
            this.InitializeComponent();
            btnConvert.Content = loader.GetString("btnConvert");
            lblAmount.Text = loader.GetString("lblAmount");
            lblFrom.Text = loader.GetString("lblFrom");
            lblTo.Text = loader.GetString("lblTo");
            populateCombo();
        }


        public async void populateCombo()
        {
            var doc = await Package.Current.InstalledLocation.GetFileAsync("Data\\Currencys.txt");
            var currencys = await Windows.Storage.FileIO.ReadLinesAsync(doc);

            cmbInput.ItemsSource = currencys;
            cmbTo.ItemsSource = currencys;
        }

        private async void btnConvert_Click(object sender, RoutedEventArgs e)
        {
            string input = cmbInput.SelectedItem.ToString();
            string to = cmbTo.SelectedItem.ToString();
            
            string[] inputCur = input.Split('(',')');
            string[] toCur = to.Split('(',')');

            if (inputCur[1] == toCur[1])
            {
                txtBResult.Text = txtInput.Text + " " + toCur[1];
            }
            else
            {
                string url = "http://quote.yahoo.com/d/quotes.cvs?s=" + inputCur[1] + toCur[1] + "=X&f=l1&e=.cvs ";

                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";

                string result = null;
                using (WebResponse response = await request.GetResponseAsync())
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    result = reader.ReadToEnd();
                }

                double cur = double.Parse(result);
                double inputValue = double.Parse(txtInput.Text);
                double resultCur = inputValue * cur;

                txtBResult.Text = resultCur.ToString() + " " + toCur[1];
            }
        }
    }
}
